package com.yzx.lifeassistants.activity;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.balysv.materialripple.MaterialRippleLayout;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.baoyz.widget.PullRefreshLayout;
import com.baoyz.widget.PullRefreshLayout.OnRefreshListener;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.yzx.lifeassistants.R;
import com.yzx.lifeassistants.adapter.MyBookAdapter;
import com.yzx.lifeassistants.base.BaseActivity;
import com.yzx.lifeassistants.bean.MyBook;
import com.yzx.lifeassistants.common.CommonConstant;
import com.yzx.lifeassistants.model.ILoginLibrary;
import com.yzx.lifeassistants.model.IRenewBook;
import com.yzx.lifeassistants.model.callback.ILoginLibraryCB;
import com.yzx.lifeassistants.model.callback.IRenewBookCB;
import com.yzx.lifeassistants.model.impl.LoginLibraryImpl;
import com.yzx.lifeassistants.model.impl.RenewBookImpl;
import com.yzx.lifeassistants.utils.DensityUtils;
import com.yzx.lifeassistants.utils.SpUtils;
import com.yzx.lifeassistants.utils.ToastUtils;
import com.yzx.lifeassistants.view.widget.CircularLoadingDialog;
import com.yzx.lifeassistants.view.widget.MySwipeMenuListView;

/**
 * @Description: 图书馆资讯
 * @author: yzx
 * @time: 2016-3-7 下午1:27:01
 */
@SuppressLint("InflateParams")
public class LibraryActivity extends BaseActivity implements OnClickListener {

	private ImageButton backBtn;// 返回按钮
	private TextView titleTV;// 标题
	private ImageButton switchAccountBtn;// 切换账号
	private RelativeLayout searchRL;// 搜索框
	private TextView noBookTV;// 暂无借阅文本
	private LinearLayout noLoginLL;// 未登录
	private PullRefreshLayout refreshLayout;// 下拉刷新
	private MySwipeMenuListView myBookLV;// 借阅列表

	private CircularLoadingDialog dialog;// 加载框
	private View contentView;// 登陆弹框
	private AlertDialog theDialog;// 登陆弹框
	private MaterialEditText usernameET;// 账号输入框
	private MaterialEditText passwordET;// 密码输入框

	private SpUtils sputil;// 保存/获取账号,密码
	private String username;// 用户名
	private String password;// 密码
	private List<MyBook> dataList;// 已借阅图书列表
	private MyBookAdapter adapter;// 已借阅图书列表适配器
	private Handler handler;
	private ILoginLibraryCB loginCallBack;// 登录回调
	private ILoginLibrary loginLibrary;// 登录图书馆
	private IRenewBookCB renewCallBack;// 续借回调
	private IRenewBook renewBook;// 续借图书

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_library);
		initView();
		setListener();
		initLoginDialog();
		initSwipeMenuListView();
		initData();
		initMaterialRipple();
	}

	/**
	 * 
	 * @Description: 初始化控件
	 */
	private void initView() {
		backBtn = (ImageButton) findViewById(R.id.top_back_btn);
		titleTV = (TextView) findViewById(R.id.top_title_tv);
		switchAccountBtn = (ImageButton) findViewById(R.id.top_switch_account_btn);
		searchRL = (RelativeLayout) findViewById(R.id.library_search_rl);
		noBookTV = (TextView) findViewById(R.id.library_no_book_tv);
		noLoginLL = (LinearLayout) findViewById(R.id.library_not_login_ll);
		refreshLayout = (PullRefreshLayout) findViewById(R.id.library_my_book_pull_refresh_layout);
		myBookLV = (MySwipeMenuListView) findViewById(R.id.library_my_book_lv);

	}

	/**
	 * 
	 * @Description: 设置监听
	 */
	private void setListener() {
		backBtn.setOnClickListener(this);
		switchAccountBtn.setOnClickListener(this);
		searchRL.setOnClickListener(this);
		noLoginLL.setOnClickListener(this);
		// 下拉刷新
		refreshLayout.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				loginLibrary(username, password);
			}

		});
		// step 2. listener item click event
		myBookLV.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(final int position, SwipeMenu menu,
					int index) {
				MyBook item = dataList.get(position);
				switch (index) {
				case 0:
					// 续借
					dialog.show();
					renewBook.renewBook(item.getBarcode());
					break;
				default:

					break;
				}
				return false;
			}
		});

		// set SwipeListener
		myBookLV.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {

			@Override
			public void onSwipeStart(int position) {
				// swipe start
			}

			@Override
			public void onSwipeEnd(int position) {
				// swipe end
			}
		});

		// set MenuStateChangeListener
		myBookLV.setOnMenuStateChangeListener(new SwipeMenuListView.OnMenuStateChangeListener() {
			@Override
			public void onMenuOpen(int position) {

			}

			@Override
			public void onMenuClose(int position) {

			}
		});

		// other setting
		// listView.setCloseInterpolator(new BounceInterpolator());

		// test item long click
		myBookLV.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {

				return false;
			}
		});
	}

	/**
	 * 
	 * @Description: 初始化登陆对话框
	 */
	private void initLoginDialog() {
		// 弹框
		theDialog = new AlertDialog.Builder(this).create();
		theDialog.setCanceledOnTouchOutside(true);
		// 设置能弹出输入法
		theDialog.setView(new EditText(this));
		contentView = LayoutInflater.from(this).inflate(R.layout.dialog_login,
				null);
		// 账号输入框
		usernameET = (MaterialEditText) contentView
				.findViewById(R.id.dialog_login_username_et);
		// 密码输入框
		passwordET = (MaterialEditText) contentView
				.findViewById(R.id.dialog_login_password_et);
		usernameET.setPaddings(DensityUtils.sp2px(this, 32), 0, 0, 0);
		passwordET.setPaddings(DensityUtils.sp2px(this, 32), 0, 0, 0);
		// 取消按钮
		Button cancleBtn = (Button) contentView
				.findViewById(R.id.dialog_login_cancle_btn);
		// 确定按钮
		Button confirmBtn = (Button) contentView
				.findViewById(R.id.dialog_login_confirm_btn);
		// 动态特效
		MaterialRippleLayout
				.on(cancleBtn)
				.rippleColor(Color.parseColor(CommonConstant.RIPPLE_COLOR_DARK))
				.rippleAlpha(CommonConstant.RIPPLE_ALPHA).rippleHover(true)
				.create();
		MaterialRippleLayout
				.on(confirmBtn)
				.rippleColor(Color.parseColor(CommonConstant.RIPPLE_COLOR_DARK))
				.rippleAlpha(CommonConstant.RIPPLE_ALPHA).rippleHover(true)
				.create();
		// 取消事件
		cancleBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				theDialog.dismiss();
			}
		});
		// 确定事件
		confirmBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				username = usernameET.getText().toString();
				password = passwordET.getText().toString();
				if (null == username || "".equals(username)) {
					showToast("请输入账号~", false);
					usernameET.requestFocus();
					return;
				}
				if (null == password || "".equals(password)) {
					showToast("请输入密码~", false);
					passwordET.requestFocus();
					return;
				}
				theDialog.dismiss();
				// 登陆
				loginLibrary(username, password);
			}

		});
	}

	/**
	 * 
	 * @Description: 初始化能左划出打开/删除的ListView
	 */
	private void initSwipeMenuListView() {
		dataList = new ArrayList<MyBook>();
		adapter = new MyBookAdapter(this, dataList);
		myBookLV.setAdapter(adapter);
		// step 1. create a MenuCreator
		SwipeMenuCreator creator = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {
				// create "续借" item
				SwipeMenuItem openItem = new SwipeMenuItem(
						getApplicationContext());
				// set item background
				openItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9,
						0xCE)));
				// set item width
				openItem.setWidth(DensityUtils.dp2px(LibraryActivity.this, 90));
				// set item title
				openItem.setTitle("续借");
				// set item title fontsize
				openItem.setTitleSize(18);
				// set item title font color
				openItem.setTitleColor(Color.WHITE);
				// add to menu
				menu.addMenuItem(openItem);

			}
		};
		// set creator
		myBookLV.setMenuCreator(creator);
	}

	/**
	 * 
	 * @Description: 初始化数据
	 */
	private void initData() {
		titleTV.setText("图书馆");
		sputil = new SpUtils(this, CommonConstant.SP_FAIL_NAME);

		dialog = new CircularLoadingDialog(this);
		handler = new Handler();
		loginCallBack = new ILoginLibraryCB() {

			@Override
			public void loginSuccess(final List<MyBook> myBookList,
					final int code) {
				handler.post(new Runnable() {

					@Override
					public void run() {
						dialog.dismiss();
						refreshLayout.setRefreshing(false);
						noLoginLL.setVisibility(View.GONE);
						switchAccountBtn.setVisibility(View.VISIBLE);
						refreshLayout.setVisibility(View.VISIBLE);
						dataList.clear();
						switch (code) {
						case ILoginLibraryCB.RESULR_NULL: {// 借阅为空
							noBookTV.setVisibility(View.VISIBLE);
							break;
						}
						case ILoginLibraryCB.LOGIN_SUCCESS: {// 获取成功
							if (null == myBookList || 1 > myBookList.size()) {
								noBookTV.setVisibility(View.VISIBLE);
							} else {
								noBookTV.setVisibility(View.GONE);
								dataList.addAll(myBookList);
							}
							break;
						}
						default:
							break;
						}
						if (null == username || "".equals(username)) {

						} else {
							sputil.setValue(
									CommonConstant.LIBRARY_USERNAME_KEY,
									username);
						}
						adapter.notifyDataSetChanged();
						if (null == password || "".equals(password)) {

						} else {
							sputil.setValue(
									CommonConstant.LIBRARY_PASSWORD_KEY,
									password);
						}

					}
				});
			}

			@Override
			public void loginError(final int code) {
				handler.post(new Runnable() {

					@Override
					public void run() {
						dialog.dismiss();
						refreshLayout.setRefreshing(false);
						showLoginDialog();
						switchAccountBtn.setVisibility(View.GONE);
						refreshLayout.setVisibility(View.GONE);
						noBookTV.setVisibility(View.VISIBLE);
						noLoginLL.setVisibility(View.VISIBLE);
						switch (code) {
						case ILoginLibraryCB.LOGIN_ERROR: {// 登录异常
							showToast("获取失败，请确认网络连接后重试~", false);
							break;
						}
						case ILoginLibraryCB.LOGIN_FAILED: {// 登录失败
							showToast("账号或密码错误~", false);
							break;
						}
						default:
							break;
						}
					}
				});
			}
		};
		loginLibrary = new LoginLibraryImpl(this, loginCallBack);

		renewCallBack = new IRenewBookCB() {

			@Override
			public void renewSuccess() {// 续借成功
				handler.post(new Runnable() {

					@Override
					public void run() {
						dialog.dismiss();
						showToast("续借成功~", true);
						loginLibrary(username, password);
					}
				});
			}

			@Override
			public void renewFailed(final int code) {// 续借失败
				handler.post(new Runnable() {

					@Override
					public void run() {
						dialog.dismiss();
						switch (code) {
						case IRenewBookCB.ALREADY_RENEW: {// 因续借过一次而续借失败
							showToast("续借失败，已续借过一次~", false);
							break;
						}
						case IRenewBookCB.RENEW_FAILED: {// 因条形码出错而续借失败
							showToast("续借失败，请确认网络连接后重试~", false);
							break;
						}
						default:
							break;
						}
					}
				});
			}
		};
		renewBook = new RenewBookImpl(this, renewCallBack);

		// 账号
		username = sputil.getValue(CommonConstant.LIBRARY_USERNAME_KEY, "");
		// 密码
		password = sputil.getValue(CommonConstant.LIBRARY_PASSWORD_KEY, "");
		if (null == username || "".equals(username) || null == password
				|| "".equals(password)) {
			switchAccountBtn.setVisibility(View.GONE);
			refreshLayout.setVisibility(View.GONE);
			noBookTV.setVisibility(View.VISIBLE);
			noLoginLL.setVisibility(View.VISIBLE);
		} else {
			loginLibrary(username, password);
		}
	}

	/**
	 * 
	 * @Description: 瓷砖特效
	 */
	private void initMaterialRipple() {
		List<View> views = new ArrayList<View>();
		views.add(noBookTV);
		views.add(noLoginLL);
		for (View view : views) {
			// 动态特效
			MaterialRippleLayout
					.on(view)
					.rippleColor(
							Color.parseColor(CommonConstant.RIPPLE_COLOR_LITHT))
					.rippleAlpha(CommonConstant.RIPPLE_ALPHA).rippleHover(true)
					.create();
		}

	}

	/**
	 * 
	 * @Description: 登录图书馆
	 */
	private void loginLibrary(String username, String password) {
		dialog.show();
		loginLibrary.loginLibrary(username, password);
	}

	/**
	 * 
	 * @Description: 按键监听
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.top_back_btn: {// 返回
			finish();
			break;
		}
		case R.id.top_switch_account_btn: {// 切换账号
			showLoginDialog();
			break;
		}
		case R.id.library_search_rl: {// 搜索
			Intent intent = new Intent(this, LibrarySearchActivity.class);
			startActivity(intent);
			break;
		}
		case R.id.library_not_login_ll: {// 未登录
			showLoginDialog();
			break;
		}
		default:
			break;
		}
	}

	/**
	 * 
	 * @Description: 弹出登录框
	 */
	private void showLoginDialog() {
		if (null == username || "".equals(username)) {

		} else {
			usernameET.setText(username);
		}
		if (null == password || "".equals(password)) {

		} else {
			passwordET.setText(password);
		}
		theDialog.show();
		theDialog.setContentView(contentView);
		theDialog.getWindow().setGravity(Gravity.CENTER);
	}

	/**
	 * 
	 * @Description: Toast显示信息
	 */
	private void showToast(String message, Boolean isInfo) {
		if (isInfo) {
			ToastUtils.showInfoToast(this, message, R.id.library_top_rl);
		} else {
			ToastUtils.showAlertToast(this, message, R.id.library_top_rl);
		}

	}
}
